package com.assets.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.assets.newNHF.util.LogUtils;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.demo.WaveSwipeRefreshLayout;
import com.assets.Adapter.Public_list_item_Adapter;
import com.assets.Shift.Allot_Add;
import com.assets.Ip_set.Url;
import com.assets.Particulars;
import com.assets.R;
import com.assets.bean.Allot_bean;
import com.assets.menu.SlideSideMenuExampleActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.*;

/**
 * Created by Administrator on 2019/3/11.
 */

public class Allot extends Fragment {
    private ImageView imageView;
    private ImageView add, screen;
    private ListView lv_list;
    List<Map<String, Object>> order = new ArrayList<Map<String, Object>>();
    List<Map<String, Object>> maintenanceing = new ArrayList<Map<String, Object>>();
    WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private SlideSideMenuExampleActivity activity;
    private String url = "http://" + Url.IP + "/api/transferQuery";//获取资产信息url

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.allot, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity = (SlideSideMenuExampleActivity) getActivity();
        SharedPreferences mm = getActivity().getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        inview();
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String str = String.valueOf(lv_list.getAdapter().getItem(position));
                String[] strs = str.split(",");
                Intent intent = new Intent(activity, Particulars.class);
                intent.putExtra("repairsId", strs[1].toString());
                intent.putExtra("state", "4");
                startActivity(intent);
            }
        });
        screen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertView("筛选", null, "取消", new String[]{"全部"}, new String[]{"申请中", "通过", "驳回"}, activity, AlertView.Style.ActionSheet, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            //适配器，刚刚重写的！
                            Public_list_item_Adapter re_ad = new Public_list_item_Adapter(activity, list);
                            lv_list.setAdapter(re_ad);
                        }
                        if (position == 3) {
                            maintenanceing.clear();
                            for (int i = 0; i < list.size(); i++) {
                                if (list.get(i).get("scope").equals("驳回")) {
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map.put("odd_tv", "转移单号");
                                    map.put("creator_tv", "数量");
                                    map.put("sum_tv", "转入部门");
                                    map.put("state_tv", "接收人");
                                    map.put("scope_tv", "状态");
                                    map.put("Date_created_tv", "申请时间");
                                    map.put("Inventory_date_tv", "存放地点");
                                    map.put("scope", list.get(i).get("scope"));
                                    map.put("state", list.get(i).get("state"));
                                    map.put("odd", list.get(i).get("odd"));
                                    map.put("Date_created", list.get(i).get("Date_created"));
                                    map.put("creator", list.get(i).get("creator"));
                                    map.put("sum", list.get(i).get("sum"));
                                    map.put("Inventory_date", list.get(i).get("Inventory_date"));
                                    maintenanceing.add(map);
                                }
                            }
                            Public_list_item_Adapter re_ad = new Public_list_item_Adapter(activity, maintenanceing);
                            lv_list.setAdapter(re_ad);
                        }
                        if (position == 2) {
                            maintenanceing.clear();
                            for (int i = 0; i < list.size(); i++) {
                                if (list.get(i).get("scope").equals("通过")) {
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map.put("odd_tv", "转移单号");
                                    map.put("creator_tv", "数量");
                                    map.put("sum_tv", "转入部门");
                                    map.put("state_tv", "接收人");
                                    map.put("scope_tv", "状态");
                                    map.put("Date_created_tv", "申请时间");
                                    map.put("Inventory_date_tv", "存放位置");
                                    map.put("scope", list.get(i).get("scope"));
                                    map.put("state", list.get(i).get("state"));
                                    map.put("odd", list.get(i).get("odd"));
                                    map.put("Date_created", list.get(i).get("Date_created"));
                                    map.put("creator", list.get(i).get("creator"));
                                    map.put("sum", list.get(i).get("sum"));
                                    map.put("Inventory_date", list.get(i).get("Inventory_date"));
                                    maintenanceing.add(map);
                                }
                            }
                            Public_list_item_Adapter re_ad = new Public_list_item_Adapter(activity, maintenanceing);
                            lv_list.setAdapter(re_ad);
                        }
                        if (position == 1) {
                            order.clear();
                            for (int i = 0; i < list.size(); i++) {
                                if (list.get(i).get("scope").equals("申请中")) {
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map.put("odd_tv", "转移单号");
                                    map.put("creator_tv", "数量");
                                    map.put("sum_tv", "转入部门");
                                    map.put("state_tv", "接收人");
                                    map.put("scope_tv", "状态");
                                    map.put("Date_created_tv", "申请时间");
                                    map.put("Inventory_date_tv", "存放位置");
                                    map.put("scope", list.get(i).get("scope"));
                                    map.put("state", list.get(i).get("state"));
                                    map.put("odd", list.get(i).get("odd"));
                                    map.put("Date_created", list.get(i).get("Date_created"));
                                    map.put("creator", list.get(i).get("creator"));
                                    map.put("sum", list.get(i).get("sum"));
                                    map.put("Inventory_date", list.get(i).get("Inventory_date"));
                                    order.add(map);
                                }
                            }
                            Public_list_item_Adapter re_ad = new Public_list_item_Adapter(activity, order);
                            lv_list.setAdapter(re_ad);
                        }
                    }
                }).show();
            }
        });
       /* lv_list.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 触摸按下时的操作

                        break;
                    case MotionEvent.ACTION_MOVE:
                        // 触摸移动时的操作
                        suspension.setVisibility(View.GONE);
                        break;
                    case MotionEvent.ACTION_UP:
                        // 触摸抬起时的操作
                        suspension.setVisibility(View.VISIBLE);
                        break;
                }
                return false;
            }
        });*/
    }

    /* private void post(final String assetNumber) {
         new Thread(new Runnable() {
             @Override
             public void run() {
                 OkHttpClient client =new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();//创建OkHttpClient对象。
                 FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                 formBody.add("assetNumber",assetNumber);
                 Request request = new Request.Builder()//创建Request 对象。
                         .url(url)
                         .post(formBody.build())//传递请求体
                         .build();
                 client.newCall(request).enqueue(new Callback() {
                     @Override
                     public void onFailure(Call call, IOException e) {
                         //回调方法的使用与get异步请求相同
                         Log.i("123123", "error");
                     }

                     @Override
                     public void onResponse(Call call, Response response) throws IOException {
                         final String responseData = response.body().string();
                         //回调方法的使用与get异步请求相同
                         handler.post(new Runnable() {
                             @Override
                             public void run() {
                             }
                         });
                     }
                 });
             }
         }).start();
     }*/
    private void inview() {
        screen = (ImageView) activity.findViewById(R.id.screen);
        imageView = (ImageView) activity.findViewById(R.id.opmenu);
        imageView.setOnClickListener((View.OnClickListener) v -> {
            SlideSideMenuTransitionLayout mSlideSideMenu = (SlideSideMenuTransitionLayout) getActivity().findViewById(R.id.slide_side_menu);
            mSlideSideMenu.toggle();
        });
        add = (ImageView) activity.findViewById(R.id.add);
        add.setOnClickListener(v -> {
            Intent intent = new Intent(activity, Allot_Add.class);
            startActivity(intent);
        });
        lv_list = (ListView) getActivity().findViewById(R.id.allot_list);
        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) getActivity().findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(() -> {
            //模拟3秒的加载过程
            //接下来可以刷新ListView
            new Handler().postDelayed(this::load, 1200);
        });
    }

    private void load() {
        new Thread() {
            @Override
            public void run() {
                try {
                    OkHttpClient client =new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userId", Since_case.getInstance().getUserId())
                            .build();
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    LogUtils.d(responseData);
                    showResponse(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void showResponse(final String responseData) {
        list.clear();
        if (responseData.equals("[]")) {
            activity.showToast("无转移单");
        }
        Gson gson = new Gson();
        List<Allot_bean> userList = gson.fromJson(responseData, new TypeToken<List<Allot_bean>>() {
        }.getType());
        for (int i = 0; i < userList.size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("odd_tv", "转移单号");
            map.put("creator_tv", "管理人");
            map.put("sum_tv", "转入部门");
            map.put("state_tv", "接收人");
            map.put("scope_tv", "状态");
            map.put("Date_created_tv", "申请时间");
            map.put("Inventory_date_tv", "存放地点");
            map.put("Transfer_time_tv","转移时间");
            map.put("odd", userList.get(i).getTransferId());
            map.put("allot_admin",userList.get(i).getAdmin());
            map.put("Date_created", userList.get(i).getRedate().substring(0, 10));
            map.put("creator", userList.get(i).getSum());
            map.put("sum", userList.get(i).getDeptId());
            map.put("createdat",userList.get(i).getCreatedat());
            map.put("Inventory_date", userList.get(i).getPlace());
            String zt = "";
            if (userList.get(i).getStatus().equals("1")) {
                zt = "申请中";
            }
            if (userList.get(i).getStatus().equals("2")) {
                zt = "审核通过，待复审";
            }
            if (userList.get(i).getStatus().equals("3")) {
                zt = "驳回";
            }
            if (userList.get(i).getStatus().equals("4")) {
                zt = "通过";
            }
            map.put("scope", zt);
            map.put("state", userList.get(i).getUserId());
            list.add(map);
        }
        Collections.reverse(list);
        Public_list_item_Adapter re_ad = new Public_list_item_Adapter(activity, list);
        activity.runOnUiThread(() -> {
            mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
            lv_list.setAdapter(re_ad);
        });

    }

    @Override
    public void onStart() {
        new Handler().postDelayed(this::load, 200);
        super.onStart();
    }
}
